package com.stxx.framwork.support;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.stxx.framwork.constants.LogicType;
import com.stxx.framwork.domain.model.PageQuery;
import com.stxx.framwork.domain.model.PageResult;
import com.stxx.framwork.utils.StoreUtils;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public interface BaseService <T,P>{
    T queryById(P id);
    int insert(T bean) throws SQLException;
    int update(T bean) throws SQLException;
    int delete(P id) throws SQLException;
    int deleteByIds(P[] ids) throws SQLException;
    List<T> list(T obj) throws SQLException;
    PageResult<T> pageList(T obj, PageQuery pageQuery) throws SQLException;

    final static Map<String, Map<String,LogicType>> configs = new HashMap();
    default void configLogic(Getter<T> getter, LogicType logicType){
        try {
            Method method = getter.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(Boolean.TRUE);
            SerializedLambda lambda = (SerializedLambda) method.invoke(getter);
            String tableName = StoreUtils.getTableName(StrUtil.toUnderlineCase(lambda.getImplClass().substring(lambda.getImplClass().lastIndexOf('/')+1)));
            String fieldName = StrUtil.toUnderlineCase(BeanUtil.getFieldName(lambda.getImplMethodName()));
            if(!configs.containsKey(tableName)){
                configs.put(tableName,new HashMap<>());
            }
            configs.get(tableName).put(fieldName,logicType);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    static <T> LogicType getLogic(String tableName,String fieldName){
        LogicType r = null;
        if(configs.containsKey(tableName)){
            r = configs.get(tableName).get(fieldName);
        }
        if(r==null){
            return LogicType.EQ;
        }
        return r;
    }

}
